package com.htandroid.htandroid.sys;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.ab.task.AbTask;
import com.ab.task.AbTaskItem;
import com.ab.task.AbTaskListListener;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.pullview.AbPullToRefreshView;
import com.htandroid.htandroid.R;
import com.htandroid.htandroid.adapter.MyAdapter_jtgl_jtsplist;
import com.htandroid.htandroid.adapter.MyAdapter_listtab;
import com.htandroid.htandroid.aty.MyBaseActivity;
import com.htandroid.htandroid.global.MyApplication;
import com.htandroid.htandroid.tools.ToolDataProvider;
import com.htandroid.htandroid.tools.ToolLog;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by lkp on 2015/11/29.
 */
public class base_index extends MyBaseActivity implements AbPullToRefreshView.OnHeaderRefreshListener,
        AbPullToRefreshView.OnFooterLoadListener {
    public MyAdapter_listtab sa;//数据样式
    public MyAdapter_jtgl_jtsplist sa2;//数据样式
    public ArrayList<Map<String, Object>> adatperDataList = new ArrayList<Map<String, Object>>();
    //存放数据工具类
    public ToolDataProvider toolDataProvider;
    public int index;
    public String listtype = "0";//当前类型
    public String jt_listtype = "1";//当前类型
    public MyApplication myApplication; //全局变量application
    public InputMethodManager imm;
    public int icurrentrow = 0;//当前行
    public View rightViewShare = null;
    public View rightViewSearch = null;
    public String myTitle = "";

    private AbPullToRefreshView mAbPullToRefreshView = null;
    public ListView mListView = null;

    private View ll_search;
    public ImageView ivDeleteText; //搜索栏清空按钮
    public EditText etSearch;
    public TextView tvTab1;
    public TextView tvTab2;
    private View linetab1;
    private View linetab2;

    public String excelPath;
    public Button btn_share;
    public Button btn_Search;
    public String imgPath;
    private boolean isSearch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    //初始化
    public void initview(final String title) {
        myApplication = (MyApplication) abApplication;//获得我们的应用程序全局变量
        titleBar.setTitleText(title);
        titleBar.setLogo(R.mipmap.icon_back);
        titleBar.clearRightView();
        rightViewSearch = mInflater.inflate(R.layout.search, null);
        rightViewSearch.setPadding(0, 0, dp2Px(15), 0);
        titleBar.addRightView(rightViewSearch);
        btn_Search = (Button) rightViewSearch.findViewById(R.id.icon_search);
        btn_Search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ll_search.setVisibility(isSearch ? View.GONE : View.VISIBLE);
                if (!isSearch) {
                    AnimationSet animationSet = new AnimationSet(true);
                    ScaleAnimation scaleAnimation = new ScaleAnimation(1, 1, 0, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.ZORDER_BOTTOM, 0.5f);
                    animationSet.setDuration(250);
                    animationSet.addAnimation(scaleAnimation);
                    ll_search.startAnimation(animationSet);
                }
                isSearch = !isSearch;
            }
        });
        rightViewShare = mInflater.inflate(R.layout.share, null);
        titleBar.addRightView(rightViewShare);
        titleBar.setTitlePadding(dp2Px(35), 0, 0, 0);
        btn_share = (Button) rightViewShare.findViewById(R.id.icon_share);
        this.myTitle = title;
        if ("供应商档案".equals(title) || "请购单明细".equals(title)
                || "日志查看".equals(title) || "厨房请购单明细".equals(title)
                || "库存申请单明细".equals(title) || "资产盘点明细".equals(title)
                || "部门档案".equals(title) || "维修区域".equals(title)
                || "维修等级".equals(title) || "维修员".equals(title)
                || "存货档案".equals(title) || "盘点人".equals(title)
                || "集团审批".equals(title)
                || ("厨房请购清单".equals(title) && "0".equals(listtype))) {
            titleBar.setTitlePadding(0, 0, 0, 0);
            rightViewSearch.setPadding(0, 0, 0, 0);
            rightViewShare.setVisibility(View.GONE);
        } else if ("维修材料".equals(title) || "外包材料".equals(title)
                || "维修工时".equals(title)) {
            rightViewSearch.setVisibility(View.GONE);
            rightViewShare.setVisibility(View.GONE);
            titleBar.setTitlePadding(0, 0, dp2Px(20), 0);
        }

        // 工具类初始化
        toolDataProvider = new ToolDataProvider();
        mAbPullToRefreshView = (AbPullToRefreshView) this.findViewById(R.id.mPullRefreshView);
        mListView = (ListView) this.findViewById(R.id.mListView);
        if ("集团审批".equals(title)) {
            sa2 = new MyAdapter_jtgl_jtsplist(getApplicationContext(), adatperDataList);
            mListView.setAdapter(sa2);
        } else {
            sa = new MyAdapter_listtab(getApplicationContext(), getChildId(), adatperDataList);
            mListView.setAdapter(sa);
        }
        tvTab1 = (TextView) findViewById(R.id.tab1);
        tvTab2 = (TextView) findViewById(R.id.tab2);
        linetab1 = findViewById(R.id.tab1_line);
        linetab2 = findViewById(R.id.tab2_line);
        ll_search = findViewById(R.id.ll_search);
        etSearch = (EditText) findViewById(R.id.etSearch);
        //搜索框
        etSearch.clearFocus();
        imm = (InputMethodManager) getSystemService(getApplicationContext().INPUT_METHOD_SERVICE);
        //搜索清除
        ivDeleteText = (ImageView) findViewById(R.id.ivDeleteText);
        ivDeleteText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //清除文字
                etSearch.getText().clear();
                etSearch.clearFocus();
                //关闭软键盘
                adatperDataList.clear();
                //刷新清空数据
                adatperDataList.addAll(toolDataProvider.getFirstPage());
                //获取第一页
                if ("集团审批".equals(myTitle)) {
                    sa2.notifyDataSetChanged();
                } else {
                    sa.notifyDataSetChanged();
                }
                imm.hideSoftInputFromWindow(etSearch.getWindowToken(), 0);
                //显示删除图片
                ivDeleteText.setVisibility(View.VISIBLE);
            }
        });

        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() == 0) {
                    ivDeleteText.setVisibility(View.INVISIBLE);
                    adatperDataList.clear();
                    //刷新清空数据
                    adatperDataList.addAll(toolDataProvider.getFirstPage());
                    //获取第一页
                } else {
                    ivDeleteText.setVisibility(View.VISIBLE);
                    String keyword = etSearch.getText().toString().trim();
                    adatperDataList.clear();
                    adatperDataList.addAll(toolDataProvider.getSearch(keyword));
                }

                if ("集团审批".equals(myTitle)) {
                    sa2.notifyDataSetChanged();
                } else {
                    sa.notifyDataSetChanged();
                }
            }
        });

        //切换监听
        tvTab1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvTab1.setTextColor(getResources().getColor(R.color.app_blue));
                linetab1.setBackgroundColor(getResources().getColor(R.color.app_blue));
                tvTab2.setTextColor(getResources().getColor(R.color.app_black));
                linetab2.setBackgroundColor(getResources().getColor(R.color.app_border));
                if ("集团审批".equals(title)) {
                    jt_listtype = "1";
                } else {
                    listtype = "0";//状态一
                }
                etSearch.getText().clear();
                if ("厨房请购清单".equals(title)) {
                    rightViewShare.setVisibility(View.GONE);
                    rightViewSearch.setPadding(0, 0, 0, 0);
                    titleBar.setTitlePadding(0, 0, 0, 0);
                }
                AbDialogUtil.showProgressDialog(base_index.this, 0, "正在加载...");
                getdata(0);
            }
        });

        tvTab2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvTab2.setTextColor(getResources().getColor(R.color.app_blue));
                linetab2.setBackgroundColor(getResources().getColor(R.color.app_blue));
                tvTab1.setTextColor(getResources().getColor(R.color.app_black));
                linetab1.setBackgroundColor(getResources().getColor(R.color.app_border));
                if ("集团审批".equals(title)) {
                    jt_listtype = "0";
                } else {
                    listtype = "1";//状态一
                }
                etSearch.getText().clear();
                if ("厨房请购清单".equals(title)) {
                    rightViewShare.setVisibility(View.VISIBLE);
                    titleBar.setTitlePadding(dp2Px(35), 0, 0, 0);
                    rightViewSearch.setPadding(0, 0, dp2Px(15), 0);
                }
                AbDialogUtil.showProgressDialog(base_index.this, 0, "正在加载...");
                getdata(0);
            }
        });

        // 设置监听器
        mAbPullToRefreshView.setOnHeaderRefreshListener(this);
        mAbPullToRefreshView.setOnFooterLoadListener(this);
    }

    private int getChildId() {
        int child = 1;
        if (TextUtils.equals(myTitle.trim(), "部门请购定价")) {
            return 1;
        }

        if (TextUtils.equals(myTitle.trim(), "部门请购审批")) {
            return 2;
        }

        // TODO: 2018/8/24 ......
        return child;
    }

    // 将excel图标保存到sd卡
    public void writeImg(String file) {
        File filePath = new File(file);
        //得到图片对象
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.excel);
        FileOutputStream fos = null;
        try {
            //创建输出流
            fos = new FileOutputStream(filePath);
            //解析图片
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void loadList() {
        AbTask mAbTask = new AbTask();
        final AbTaskItem item = new AbTaskItem();

        item.setListener(new AbTaskListListener() {
            @Override
            public List<?> getList() {
                List<Map<String, Object>> newList = null;
                try {
                    Thread.sleep(1000);
                    newList = toolDataProvider.getFirstPage();
                } catch (Exception e) {
                }
                return newList;
            }

            @Override
            public void update(List<?> paramList) {
                //AbLogUtil.d(base_index.class, "返回", true);
                List<Map<String, Object>> newList = (List<Map<String, Object>>) paramList;
                adatperDataList.clear();
                if (newList != null && newList.size() > 0) {
                    adatperDataList.addAll(newList);
                    if ("集团审批".equals(myTitle)) {
                        sa2.notifyDataSetChanged();
                    } else {
                        sa.notifyDataSetChanged();
                    }
                    newList.clear();
                }
                mAbPullToRefreshView.onHeaderRefreshFinish();
                AbDialogUtil.removeDialog(base_index.this);
            }
        });
        mAbTask.execute(item);
    }

    public void loadMoreTask() {
        AbTask mAbTask = new AbTask();
        final AbTaskItem item = new AbTaskItem();
        item.setListener(new AbTaskListListener() {

            @Override
            public void update(List<?> paramList) {
                AbDialogUtil.removeDialog(base_index.this);
                List<Map<String, Object>> newList = (List<Map<String, Object>>) paramList;
                if (newList != null && newList.size() > 0) {
                    adatperDataList.addAll(newList);
                    if ("集团审批".equals(myTitle)) {
                        sa2.notifyDataSetChanged();
                    } else {
                        sa.notifyDataSetChanged();
                    }
                    mAbPullToRefreshView.onFooterLoadFinish(newList.size());
                    newList.clear();
                } else {
                    mAbPullToRefreshView.onFooterLoadFinish(newList.size());
                }
            }

            @Override
            public List<?> getList() {
                List<Map<String, Object>> newList = null;
                try {
                    Thread.sleep(1000);
                    newList = toolDataProvider.getNext();
                    ToolLog.log("------------------------------------size:" + newList.size());
                } catch (Exception e) {
                    newList.clear();
                    AbToastUtil.showToastInThread(getApplicationContext(), e.getMessage());
                }
                return newList;
            }
        });
        mAbTask.execute(item);
    }

    @Override
    public void onFooterLoad(AbPullToRefreshView view) {
        loadMoreTask();
    }

    @Override
    public void onHeaderRefresh(AbPullToRefreshView view) {
        getdata(0);
    }


    //单独处理一个初始化,便于重写的初始化事件处理
    public void initview2() {

    }

    //获取数据,因为每个列表获取数据方式不一样.所以这个函数都需要重写
    public void getdata(int page) {

    }

    //行选择事件
    public void linechoose(String ctype, int id) {
        if ("集团审批".equals(myTitle)) {
            if (ctype.equals("m")) {
                //多选,第一次选中,第二次取消
                sa2.getIsSelected().put(id, !sa2.getIsSelected().get(id));
            } else {
                //单选
                //先恢复当前行选中
                sa2.getIsSelected().put(icurrentrow, false);
                //重新选中
                sa2.getIsSelected().put(id, true);
            }
            icurrentrow = id;
            sa2.notifyDataSetChanged();
        } else {
            if (ctype.equals("m")) {
                //多选,第一次选中,第二次取消
                sa.getIsSelected().put(id, !sa.getIsSelected().get(id));
            } else {
                //单选
                //先恢复当前行选中
                sa.getIsSelected().put(icurrentrow, false);
                //重新选中
                sa.getIsSelected().put(id, true);
            }
            icurrentrow = id;
            sa.notifyDataSetChanged();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public void onPause() {
        super.onPause();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            this.finish();
        }
        return false;
    }
}
